package com.example.letswalk.shiro.filter;


import com.example.letswalk.service.SysMenuService;
import com.example.letswalk.util.SpringContextUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;


import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.util.Set;


public class URLPathMatchingFilter extends PathMatchingFilter {
	@Autowired
	SysMenuService sysMenuService;

	@Override
	protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		if(null==sysMenuService)
			sysMenuService = SpringContextUtils.getContext().getBean(SysMenuService.class);

		String requestURI = getPathWithinApplication(request);
		//System.out.println("requestURI:" + requestURI);

		Subject subject = SecurityUtils.getSubject();
		// 如果没有登录，就跳转到登录页面
		if (!subject.isAuthenticated()) {
			WebUtils.issueRedirect(request, response, "/login");
			return false;
		}

		// 看看这个路径权限里有没有维护，如果没有维护，一律放行(也可以改为一律不放行)
		//System.out.println("sysMenuService:"+sysMenuService);
		boolean needInterceptor = sysMenuService.needInterceptor(requestURI);


			boolean hasPermission = false;
			String userName = subject.getSession().getAttribute("currectuser").toString();
			Set<String> permissionUrls = sysMenuService.listPermissionURLs(userName);
			for (String url : permissionUrls) {
				// 这就表示当前用户有这个权限
                //System.out.println("qqqqqqqqqqqqqqqqqq"+url);
                if (url.equals(requestURI)) {
					hasPermission = true;
					break;
				}
			}

      // System.out.println("zlddx"+hasPermission);
        if (hasPermission==true)
				return true;
			else {
                WebUtils.issueRedirect(request, response, "/unauthorized");
                return false;
			}

		}

	}
